/*
 * author      : dormi330
 * date        : 2018/6/29
 * project     : mybatis
 * description : 分布式锁服务, 这里的实现是【错误】的。
 */

package com.deep.trade.adaptor.required;

import com.deep.trade.common.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DistributeLockService {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private static final String DEFAULT_LOCK = "_default_lock_";
    private final Map<String, Object> lockMap = new HashMap<>();
    private final List<String> lockList = new ArrayList<>();

    public boolean getLock() {
        return this.getLock(DEFAULT_LOCK);
    }

    public boolean releaseLock() {
        return this.releaseLock(DEFAULT_LOCK);
    }

    // 如果lockList中无此lockName, 则获取锁, 否则得不到锁
    public boolean getLock(String lockName) {
        logger.warn("{}, lockName= {}", CommonUtils.currentClassAndMethod(), lockName);
        if (null == lockName) lockName = DEFAULT_LOCK;
        synchronized (lockList) {
            if (lockList.indexOf(lockName) == -1) {
                return lockList.add(lockName);
            }
        }
        return false;
    }

    // 如果lockList中有lockName, 则释放锁, 否则失败
    public boolean releaseLock(String lockName) {
        logger.warn("{}, lockName= {}", CommonUtils.currentClassAndMethod(), lockName);
        if (null == lockName) lockName = DEFAULT_LOCK;
        synchronized (lockList) {
            if (lockList.indexOf(lockName) != -1) {
                return lockList.remove(lockName);
            }
        }
        return false;
    }
}
